package cn.edu.scau.cmi.linyiqu.adapter;

import java.util.ArrayList;
import java.util.List;

import cn.edu.scau.cmi.linyiqu.adapter.AdapterOfClass;
import cn.edu.scau.cmi.linyiqu.adapter.AdapterOfObject;
import cn.edu.scau.cmi.linyiqu.adapter.Adaptee;
import cn.edu.scau.cmi.linyiqu.adapter.Student;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.Accordion;
import javafx.scene.control.Button;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.control.TitledPane;

public class Controller {
	@FXML
	private Accordion accordion;

	@FXML
	private TitledPane titledPane;

	@FXML
	private TextField classAdapterNameTextField;

	@FXML
	private TextField classAdapterIDTextField;

	@FXML
	private Button classAdapterButton;

	@FXML
	private TextArea classAdapterTextArea;

	@FXML
	private TextField objectAdapterNameTextField;

	@FXML
	private TextField objectAdapterIDTextField;

	@FXML
	private Button objectAdapterButton;

	@FXML
	private TextArea objectAdapterTextArea;

	private List<Student> classAdapterStudentList = new ArrayList<>();
	private List<Student> objectAdapterStudentList = new ArrayList<>();
	private Adaptee adapter;

	public void init()
	{
		accordion.setExpandedPane(titledPane);
		classAdapterButton.setOnAction(this::createNewStudentOfClassAdapter);
		objectAdapterButton.setOnAction(this::createNewStudentOfObjectAdapter);
	}

	private void createNewStudentOfClassAdapter(ActionEvent actionEvent)
	{
		if (classAdapterNameTextField.getText().equals(""))
			return;
		try
		{
			Integer.parseInt(classAdapterIDTextField.getText());
		}
		catch (NumberFormatException e)
		{
			return;
		}
		classAdapterStudentList.add(
				new Student(Integer.parseInt(classAdapterIDTextField.getText()),
							classAdapterNameTextField.getText()));
		adapter = new AdapterOfClass();
		adapter.sortStudent(classAdapterStudentList);
		classAdapterTextArea.setText("");
		for (Student student : classAdapterStudentList)
		{
			classAdapterTextArea.setText(
					classAdapterTextArea.getText() + student.toString() + "\n");
		}
	}

	private void createNewStudentOfObjectAdapter(ActionEvent actionEvent)
	{
		if (objectAdapterNameTextField.getText().equals(""))
			return;
		try
		{
			Integer.parseInt(objectAdapterIDTextField.getText());
		}
		catch (NumberFormatException e)
		{
			return;
		}
		objectAdapterStudentList.add(
				new Student(Integer.parseInt(objectAdapterIDTextField.getText()),
												 objectAdapterNameTextField.getText()));
		adapter = new AdapterOfObject();
		adapter.sortStudent(objectAdapterStudentList);
		objectAdapterTextArea.clear();
		for (Student student : objectAdapterStudentList)
		{
			objectAdapterTextArea.setText(
					objectAdapterTextArea.getText() + student.toString() + "\n");
		}
	}
}
